package com.warmheart.base.config;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

@Configuration
@AutoConfigureAfter({ WhJdbcConfig.class, WhDruidConfig.class })
@EnableTransactionManagement
public class DataBaseConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(DataBaseConfiguration.class);

    @Bean(name = "dataSource", destroyMethod = "close", initMethod = "init")
    public DataSource writeDataSource(WhJdbcConfig whJdbcConfig, WhDruidConfig whDruidConfig) {
        long startTime = System.currentTimeMillis();
        DruidDataSource datasource = new DruidDataSource();
        datasource.setDriverClassName(whJdbcConfig.getDriver());
        datasource.setUrl(whJdbcConfig.getUrl());
        datasource.setUsername(whJdbcConfig.getUsername());
        datasource.setPassword(whJdbcConfig.getPassword());
        setDruidDataSource(datasource, whDruidConfig);
        logger.info("......configuring dataSource end time is:{}ms......", (System.currentTimeMillis() - startTime));
        return datasource;
    }

    private void setDruidDataSource(DruidDataSource datasource, WhDruidConfig whDruidConfig) {
        long startTime = System.currentTimeMillis();
        try {
            datasource.setInitialSize(whDruidConfig.getInitialSize());
            datasource.setMinIdle(whDruidConfig.getMinIdle());
            datasource.setMaxActive(whDruidConfig.getMaxActive());
            datasource.setMaxWait(whDruidConfig.getMaxWait());
            datasource.setTimeBetweenEvictionRunsMillis(whDruidConfig.getTimeBetweenEvictionRunsMillis());
            datasource.setMaxEvictableIdleTimeMillis(whDruidConfig.getMaxEvictableIdleTimeMillis());
            datasource.setMinEvictableIdleTimeMillis(whDruidConfig.getMinEvictableIdleTimeMillis());
            datasource.setValidationQuery(whDruidConfig.getValidationQuery());
            datasource.setTestWhileIdle(whDruidConfig.getTestWhileIdle());
            datasource.setTestOnBorrow(whDruidConfig.getTestOnBorrow());
            datasource.setTestOnReturn(whDruidConfig.getTestOnReturn());
            datasource.setPoolPreparedStatements(whDruidConfig.getPoolPreparedStatements());
            datasource.setRemoveAbandoned(whDruidConfig.getRemoveAbandoned());
            if (whDruidConfig.getRemoveAbandoned()) {
                datasource.setRemoveAbandonedTimeout(whDruidConfig.getRemoveAbandonedTimeout());
            }
            datasource.setFilters(whDruidConfig.getFilters());
            datasource.setConnectionProperties(whDruidConfig.getConnectionProperties());
            datasource.setUseGlobalDataSourceStat(whDruidConfig.getUseGlobalDataSourceStat());
        } catch (SQLException e) {
            logger.error("......set druid datasource data is error......", e);
        }
        logger.info("......set druid datasource data end time is:{}ms......", (System.currentTimeMillis() - startTime));
    }
    
    /**
     * 
     * @Title: DruidStatViewServle
     * @Description: 注册StatViewServlet
     * @author ZhangJianyang
     * @return
     */
    @Bean
    public ServletRegistrationBean<StatViewServlet> DruidStatViewServle(WhDruidConfig whDruidConfig) {
        // 访问路径
        ServletRegistrationBean<StatViewServlet> servletRegistrationBean = new ServletRegistrationBean<StatViewServlet>(
                new StatViewServlet(), "/druid/*");
        // 访问白名单（这里只可本机地址访问）
        servletRegistrationBean.addInitParameter("allow", whDruidConfig.getAllowIp());
        // 登录查看信息的账号
        servletRegistrationBean.addInitParameter("loginUsername", whDruidConfig.getUserName());
        // 登录查看信息的密码
        servletRegistrationBean.addInitParameter("loginPassword", whDruidConfig.getPassWd());
        // 是否能够重置数据（这里允许）
        servletRegistrationBean.addInitParameter("resetEnable", "true");
        return servletRegistrationBean;
    }

    /**
     * 
     * @Title: druidStatFilter
     * @Description: 注册一个监控过滤器
     * @author ZhangJianyang
     * @return
     */
    @Bean
    public FilterRegistrationBean<WebStatFilter> druidStatFilter() {
        FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<WebStatFilter>(
                new WebStatFilter());
        // 添加过滤规则.
        filterRegistrationBean.addUrlPatterns("/*");
        // 添加排除的格式信息
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}